import "dart:async";

import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/apartment/api.dart";
import "package:ct_pa_majordomo/pages/device/electricity_meter/api.dart";
import "package:ct_pa_majordomo/pages/device/electricity_meter/detail/index.dart";
import "package:ct_pa_majordomo/pages/device/electricity_meter/widgets/list_item.dart";
import "package:ct_pa_majordomo/pages/device/widgets/device_header.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/event_bus.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/empty_data/index.dart";
import "package:ct_pa_majordomo/widgets/filter_layout/filter_dropdown.dart";
import "package:ct_pa_majordomo/widgets/filter_layout/filter_header.dart";
import "package:ct_pa_majordomo/widgets/filter_layout/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";

class ElectricityMeter extends StatefulWidget {
  const ElectricityMeter({super.key});

  @override
  State<StatefulWidget> createState() => _ElectricityMeterState();

}

class _ElectricityMeterState extends State<ElectricityMeter> {

  final ScrollController _scrollController = ScrollController();
  late StreamSubscription _subscription;
  bool _isLoading = false;
  final Map _filter = {"pageNum": 1};
  List _groups = [];
  final List _lockStatus = [{"name": "全部"}, {"name": "未关联房间"}];
  List _list = [];
  int _total = 0;

  final List<FilterHeaderItem> _headerItems = [
    // FilterHeaderItem(title: "分组"),
    FilterHeaderItem(title: "状态"),
    FilterHeaderItem(
      title: "数量：0",
      render: (title) {
        return Text(
          title,
          textAlign: TextAlign.center,
          style: const TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w500,
          ),
        );
      },
    ),
  ];


  Future<void> _getGroups() async {
    try {
      // EasyLoading.show();
      List resData = await apartmentApi.getGroups();
      // EasyLoading.dismiss();
      setState(() => _groups = resData..insert(0, {"groupName": "全部"}));
    } catch (error) {
      print(error);
    }
  }

  Future<void> _getElectricityList() async {
    try {
      EasyLoading.show();
      Map<String, dynamic> params = {..._filter, "pageSize": 10};
      _isLoading = true;
      Map resData = await electricityMeterApi.getElectricityMeterList(params);
      _isLoading = false;
      EasyLoading.dismiss();
      List data = resData["rows"] ?? [];
      setState(() {
        _total = resData["total"] ?? 0;
        _headerItems.last.title = "数量：$_total";
        _list.addAll(data);
      });
    } catch (error) {
      print(error);
    }
  }

  Future<void> _refresh() async {
    _filter["pageNum"] = 1;
    _list = [];
    _getElectricityList();
  }

  void _onScroll() {
    if (_isLoading || _list.length >= _total) return;
    if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
      setState(() {
        _filter["pageNum"] += 1;
        _getElectricityList();
      });
    }
  }

  // 处理电表名称更新事件
  void _handleElectricityMeterEvent(ElectricityMeterEvent event) {
    if (event.type == "nameChanged" || event.type == "refreshInfo") {
      // 如果是当前电表的名称更新事件
      _refresh();
    }
  }

  @override
  void initState() {
    super.initState();
    _getGroups();
    _getElectricityList();
    _scrollController.addListener(_onScroll);

    // 订阅电表事件
    _subscription = eventBus.on.listen((event) {
      if (event is ElectricityMeterEvent) {
        _handleElectricityMeterEvent(event);
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
    _subscription.cancel();
  }


  @override
  Widget build(BuildContext context) {
    return DeviceHeader(
      title: "智能电表",
      leading: IconButton(
        icon: const Icon(Icons.arrow_back_ios_new),
        onPressed: () {
          Navigator.pop(context);
        },
      ),
      onSearch: (value) {
        setState(() {
          _filter["pageNum"] = 1;
          _filter["name"] = value;
        });
        _getElectricityList();
      },
      showFloatBtn: true,
      floatOnPress: () {
        Stacker.pushNamed(Keys.DEVICE_ELECTRICITYMETER_ADD)
            .then((refresh) {
              if (refresh != null && refresh as bool) {
                _refresh();
              }
        });
      },
      children: [
        FilterLayout(
          headerItems: _headerItems,
          dropdownItems: [
            // FilterDropdownItem(
            //   items: _groups,
            //   itemAsString: (item) => item["groupName"],
            //   compare: (item) => item["groupId"] == _filter["groupId"],
            //   onChanged: (item) => setState(() {
            //     _filter["groupId"] = item["groupId"];
            //   }),
            // ),
            FilterDropdownItem(
              items: _lockStatus,
              itemAsString: (item) => item["name"],
            ),
          ],
          child: RefreshIndicator(
            onRefresh: _refresh,
            child: _list.isEmpty ? ListView(
              children: [ EmptyData() ],
            ) : ListView.separated(
              padding: const EdgeInsets.all(ThemeVars.paddingPage),
              itemBuilder: (context, index) {
                return GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    Stacker.pushNamed(Keys.DEVICE_ELECTRICITYMETER_DETAIL, arguments: _list[index]["electricityMeterId"]).then((value) {
                      if (value != null && value as bool) _refresh();
                    });
                  },
                  child: ListItem(lock: _list[index],),
                );
              },
              separatorBuilder: (context, index) => const SizedBox(height: 15),
              itemCount: _list.length,
            ),
          )
        ),
      ]
    );
  }

}